package com.ruoyi.demo.controller;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.demo.mapper.TakePhotoMapper;
import com.ruoyi.demo.pojo.Result;
import com.ruoyi.demo.service.IFaceService;
import com.ruoyi.demo.service.impl.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/demo/photos")
public class PhotoController extends BaseController {

    // Python 服务地址
    @Value("${flask.host}")
    private String pythonServiceUrl;
    @Autowired
    private TakePhotoMapper takePhotoMapper;
    @Autowired
    private IFaceService faceService;
    @Autowired
    private PhotoService photoService;

    //添加人脸数据
    @PostMapping("/upload")
    public Result addFace(
            @RequestParam("image") MultipartFile image) throws IOException {
        System.out.println("上传人脸图像");
        return faceService.faceAdd(image, String.valueOf(getUserId()),"","");
    }
    @PostMapping("/recognize")
    public Result recognize(
            @RequestParam("file") MultipartFile image
    ) throws IOException {
        System.out.println("识别");
        Result result = faceService.faceRecognize(image);
        if("3".equals(result.getStatus())){
            List<Integer> integer = takePhotoMapper.selectMeetId();
            for (Integer meetId : integer) {
                // 检查 meet_user 表中是否存在对应的 user_id 和 meet_id
                Integer existMeetId = takePhotoMapper.findMeetUserByUserIdAndMeetId(Integer.parseInt(result.getMessage()), meetId);
                if (existMeetId != null) {
                    // 如果存在，执行更新操作
                    takePhotoMapper.updateMeetUser(existMeetId, Integer.parseInt(result.getMessage()));
                    break; // 如果只需要更新第一个符合条件的记录，可以加 break
                }
            }
            String userName = takePhotoMapper.selectUserNameById(Long.valueOf(result.getMessage()));
            result.setMessage(userName+"识别成功");
        }else {
            System.out.println(result.getStatus());
            result.setMessage("用户未录入人脸");
        }

        return result;
    }
    @GetMapping("/run-python")
    public String runPythonScript(@RequestParam String scriptPath) {
        return faceService.runPythonScript(scriptPath);
    }
}
